import logging

from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from .models import OAuthQQUser
from .utils import OAuthQQ
from .exceptions import QQAPIError
from .serializers import OAuthQQUserSerializer
from carts.utils import merge_cart_cookie_to_redis

logger = logging.getLogger("django")


#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """
    获取QQ登录的url  ?next=xxx
    """
    def get(self, request):
        """提供用于qq登录的url"""
        next = request.query_params.get("next")
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()
        return Response({"login_url": login_url})


class QQAuthUserView(CreateAPIView):
    """
    QQ登录的用户   ?code=xxx
    """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        # 获取code
        code = request.query_params.get("code")
        if not code:
            return Response({"message": "缺少code"}, status=status.HTTP_400_BAD_REQUEST)
        # 根据code获取access_token
        oauth = OAuthQQ()
        try:
            access_token = oauth.get_access_token(code)
            # 根据access_token获取openid
            openid = oauth.get_openid(access_token)
        except QQAPIError:
            return Response({"message": "访问QQ接口异常"},
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            # 根据openid查询数据库OAuthQQUser,判断数据是否存在
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 不存在,出来openid并返回
            generate_access_token = oauth.generate_save_user_token(openid)
            return Response({"access_token": generate_access_token})
        # 存在, 表示用户已绑定过身份,签发JWT token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        user = oauth_qq_user.user
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # return Response({
        #     "username": user.username,
        #     "user_id": user.id,
        #     "token": token
        # })
        response = Response({
            "username": user.username,
            "user_id": user.id,
            "token": token
        })
        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)
        return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        user = self.user
        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)
        return response

